<template>
	<view>
		<Navbar></Navbar>
		<view class="u-form-box u-m-30">
			<u-form :model="form" label-width="200" ref="uForm">
				<u-form-item required label="姓名">
					<u-input placeholder="请输入真实姓名" input-align="right" :clearable="false" v-model="form.name" />
				</u-form-item>
				<u-form-item  label="公司名称">
					<view :class="form.company ? '' : 'u-color-gray'">
						<u-input :clearable="false" input-align="right" placeholder="请输入公司完整名称"
							v-model="form.company"></u-input>
					</view>
				</u-form-item>
				<u-form-item  label="职位">
					<u-input placeholder="请输入职位" v-model="form.position" :clearable="false" input-align="right" />
				</u-form-item>
				<u-form-item label="身份证号" prop="id_card">
					<u-input v-model="form.id_card" placeholder="请输入身份证号码" maxlength="18" input-align="right"
						:clearable="false" />
				</u-form-item>
				<!-- <u-form-item required label="青创私董推荐人">
					<view class="u-text-right u-text-line-15 reference_name"
						:class="reference.name ? '' : 'u-color-gray'" @click="openReference">
						{{ reference.name || '请选择青创私董推荐人 >'}}
					</view>
				</u-form-item> -->
			</u-form>
		</view>
		<view class="u-p-30 u-m-30 u-font-bold u-form-box u-relative">
			<view class="require u-flex u-row-between" v-if="addressData.id">
				<view>
					<view>{{ addressData.city }}</view>
					<view class="u-m-t-5 u-m-b-5 u-font-38">{{ addressData.address }}</view>
					<view>
						<span class="u-m-r-5">{{ addressData.name }}</span>
						<span>{{ addressData.phone }}</span>
					</view>
				</view>
				<view class="u-m-l-20" @click="onEditAddress(addressData.id)">
					<u-icon name="edit-pen" size="40"></u-icon>
				</view>
			</view>
			<view class="require u-flex u-row-between" @click="onSwitchAddress()" v-else>
				<view class="u-font-bold">暂无收货信息，点击新建</view>
				<u-icon name="arrow-right"></u-icon>
			</view>
		</view>
		<!-- <view class="u-form-box u-m-30">
			<u-form>
				<u-form-item required label-position="top" label="申请成为青创私董的理由">
					<u-input v-model="form.reason" type="textarea" height="160" :auto-height="true"
						placeholder="请输入您申请成为青创私董的原因" :clearable="false" :custom-style="customStyle" />
				</u-form-item>
			</u-form>
		</view>
		
		<view class="u-form-box u-p-l-20 u-m-30">
			<view class="sign_box" @click="onOpenAgreeMent">
				<view class="agree_name u-font-bold">《青创私董申请协议》</view>
				<view :class="form.pdf ? 'u-color-puce' : 'u-color-gray'">{{ form.pdf ? '已签署' : '未签署'}}</view>
			</view>
		</view> -->

		<view style="height: 200rpx;"></view>
		<!-- <Bottom :isTwice="true" :isClick="isClick" :rightText="btnText" @confirm="confirm"></Bottom> -->
		<view class="bottom_box">
			<view class="u-width-100 u-flex u-row-between">
				<view class="confirm_btn u-m-r-30 common_css u-flex-1" @click="onBankText">{{bankText}}</view>
				<view class="confirm_btn common_css u-flex-1" @click="onWechatPay">{{btnText}}</view>
			</view>
		</view>

		<!-- 推荐人 -->
		<u-popup v-model="reference.show" mode="bottom" border-radius="20">
			<view class="checkAddressBox">
				<u-search v-model="reference.keyword" placeholder="请输入推荐人关键词" @search="searchReference"
					@clear="clearReference" @custom="searchReference"></u-search>
				<scroll-view scroll-y="true" style="height: 700rpx;margin-bottom: 60rpx;"
					@scrolltolower="loadReference">
					<view class="slot-content">
						<view :class="item.check ? 'address_check_box' : 'address_box'" v-for="item in reference.list"
							:key="item.id">
							<view @click="checkReference(item)">{{item.name}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="u-flex">
					<view class="addBtn" @click="reference.show = false">取消</view>
					<view class="bottomBtn" @click="confirmReference">确定</view>
				</view>
			</view>
		</u-popup>

		<!-- 结果弹窗 -->
		<u-modal v-model="modalShow" width="70%" :title="title" :confirm-color="'#fb6316'" :title-style="titleStyle"
			:show-cancel-button="false" :content="'您的青创私董申请已提交，工作人员将在一个工作日内完成审核，请耐心等候'" @confirm="modalConfirm">
		</u-modal>

		<!-- 省市区 -->
		<UniAddressSelector v-if="showUniAddressSelector" :selectAreaLevelLimit="3" :isSZ="0" @cancel="handleCancel"
			@confirm="handleConfirmArea" @selectArea="selectArea"></UniAddressSelector>

		<!-- 入群二维码 -->
		<u-popup v-model="joinCode.show" mode="center" border-radius="20" :mask-close-able="false" :closeable="true"
			close-icon-size="40" width="90%" @close="onCloseJoinCode">
			<view class="u-p-20 u-p-t-60">
				<view class="u-m-t-20 u-m-b-20 u-font-bold u-font-32 u-text-center">请扫码添加负责人，参加青创私董培训</view>
				<u-image class="u-m-t-20 u-width-100" :src="joinCode.image" mode="widthFix"></u-image>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Navbar from '@/components/Navbar.vue'
	import Bottom from '@/components/Bottom.vue'
	import Modal from '@/components/Modal.vue'
	import UniAddressSelector from '@/teaBureau/components/UniAddressSelector.vue'
	import env from '@/network/env.js'
	import {
		presidentList,
		teaOrderSn,
		teaCreateOrder,
		teaAdressAdd,
		teaPresidentEcho
	} from '@/network/tea.js'
	import {
		userInfo,
		getConfigInfo
	} from '@/network/api.js'
	import {
		debounce,
		hasEmptyValue,
		openDocumentPdf
	} from '@/utils/index.js'
	export default {
		components: {
			Navbar,
			Bottom,
			Modal,
			UniAddressSelector
		},
		data() {
			return {
				userId: uni.getStorageSync("user_id"),
				userData: {},
				form: {
					name: '',
					company: '',
					position: '',
					id_card: '',
				},
				// 收货地址
				addressData: {},
				// 推荐人
				reference: {
					show: false,
					keyword: '',
					list: [],
					page: 1,
					pageSize: 10,
					name: '',
					id: '',
					inviteId: '' // 青创私董邀请注册通道
				},
				// 身份证验证
				rules: {
					id_card: [{
							required: false,
							message: '请输入身份证号',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								// 身份证正则表达式
								const idCardRegex =
									/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[012]))(([0|1|2]\d)|3[01])\d{3}([0-9]|X|x)$/;
								return idCardRegex.test(value);
							},
							message: '身份证格式不正确',
							trigger: ['blur', 'change']
						}
					],
				},
				cityObj: {},
				areaObj: {},
				latitude: 0,
				longitude: 0,
				remark: '',
				imageList: [],
				showChooseCompany: false,
				companyList: [],
				customStyle: {
					background: '#F2F5FA',
					borderRadius: '20rpx',
					padding: '20rpx',
					margin: '10rpx 0 0 0'
				},
				modalShow: false,
				title: '温馨提示',
				titleStyle: {
					color: '#fb6316',
					fontSize: '40rpx',
					fontWeight: 'bold'
				},
				joinCode: {
					show: false,
					image: ''
				},
				showUniAddressSelector: false,
				action: `${env.baseUrl}/api/uploadOssImage`,
				btnText: '微信支付',
				bankText: '银行转账',
				isClick: true
			}
		},
		async onLoad(options) {
			// this.getPresidentList()
			// this.getUserInfo()
			this.getJoinCodeImage()
			if (options.id) {
				this.reference.inviteId = options.id
				const res = await userInfo({
					user_id: options.id
				})
				this.reference.name = res.data.name
				this.reference.id = res.data.id
			}
		},
		onShow() {
			this.getUserInfo()
		},
		onReady() {
			// this.$refs.uForm.setRules(this.rules);
			// this.$refs.form2.setRules(this.rules2);
		},
		methods: {
			async getUserInfo() {
				const params = {
					user_id: this.userId,
					type: 1
				}
				const res = await teaPresidentEcho(params)
				const userRes = await userInfo({
					user_id: this.userId
				})
				// 不是邀请通道
				if (res.data && !this.reference.inviteId && res.data.reference_id) {
					this.reference.id = res.data.reference_arr.id
					this.reference.name = res.data.reference_arr.name
				}
				this.userData = res.data ? res.data : userRes.data
				this.form.name = this.userData.name
				this.form.company = this.userData.company
				this.form.position = this.userData.position
				this.form.id_card = this.userData.id_card
				if (userRes.data.user_add.is_have == 1) {
					this.addressData = userRes.data.user_add.add
					this.addressData.city = this.addressData.address.substring(0, this.addressData.address.indexOf(
						"区") + 1)
					this.addressData.address = this.addressData.address.substring(this.addressData.address.indexOf(
						"区") + 1, this.addressData.address.length)
				}
				this.getPrice()
			},
			getJoinCodeImage() {
				getConfigInfo({
					key: 'join_code'
				}).then(res => {
					this.joinCode.image = res.data.value
				})
			},
			choosePlace() {
				let _this = this
				uni.chooseLocation({
					success(res) {
						_this.form.place = res.name
						_this.form.latitude = res.latitude
						_this.form.longitude = res.longitude
					}
				})
			},
			getPresidentList() {
				const params = {
					is_president: 1,
					keyword: this.reference.keyword,
					page: this.reference.page,
					limit: this.reference.pageSize
				}
				presidentList(params).then(res => {
					res.data.list.map(item => {
						const params = {
							...item,
							check: false
						}
						this.reference.list.push(params)
					})
				})
			},
			async getPrice() {
				const res = await getConfigInfo({
					key: this.reference.id ? 'have_recommend' : 'no_recommend'
				})
				this.btnText = `微信支付${res.data.value}元`
				this.bankText = `银行转账${res.data.value}元`
			},
			modalConfirm() {
				this.modalShow = false
				getApp().globalData.switchCustom = true
				uni.switchTab({
					url: "/pages/home/home"
				})
			},
			onCloseJoinCode() {
				this.joinCode.show = false
				getApp().globalData.switchCustom = true
				/* uni.switchTab({
					url: "/pages/home/home"
				}) */
				uni.reLaunch({
					url: "/teaBureau/teaPresidentCenter/teaPresidentCenter"
				})
			},
			openProvince() {
				this.showUniAddressSelector = true
			},
			handleCancel() {
				this.showUniAddressSelector = false;
			},
			handleConfirmArea(val) {
				this.showUniAddressSelector = false;
				this.form.area = val.fullAreaText
				this.provinceObj = val.provinceObj
				this.cityObj = val.cityObj
				this.areaObj = val.areaObj
			},
			selectArea(val) {
				this.showUniAddressSelector = false;
				this.form.area = val.fullAreaText
				this.provinceObj = val.provinceObj
				this.cityObj = val.cityObj
				this.areaObj = val.areaObj
			},
			handleGetCompanyName(name) {
				this.form.company = name
				this.showChooseCompany = false
			},
			onSuccess(val) {
				this.imageList.push(val.data.url)
			},
			onRemove(val) {
				this.imageList.splice(val, 1)
			},
			openReference() {
				if (this.reference.inviteId) {
					return
				} else {
					this.reference.show = true
				}
			},
			searchReference() {
				this.reference.list = []
				this.reference.page = 1
				if (this.reference.keyword) {
					this.getPresidentList()
				} else {
					uni.showToast({
						title: "请输入推荐人关键词",
						icon: "none"
					})
				}
			},
			clearReference() {
				this.reference.keyword = ''
				this.reference.list.length = 0
				this.reference.page = 1
				this.getPresidentList()
			},
			loadReference() {
				this.reference.page++
				this.getPresidentList()
			},
			checkReference(val) {
				this.reference.list.map(item => item.check = false)
				val.check = true
			},
			confirmReference() {
				let checkObj = this.reference.list.find(item => item.check == true)
				this.reference.name = checkObj.name
				this.reference.id = checkObj.id
				this.reference.show = false
				this.getPrice()
			},
			onSwitchAddress() {
				uni.navigateTo({
					url: "/teaBureau/teaAddressList/teaAddressList?type=1"
				})
			},
			onEditAddress(id) {
				uni.navigateTo({
					url: "/teaBureau/teaAddressForm/teaAddressForm?id=" + id
				})
			},
			onOpenAgreeMent() {
				if (this.form.pdf) {
					openDocumentPdf(this.form.pdf)
				} else {
					if (this.form.name && uni.getStorageSync("user_phone")) {
						const params = {
							name: this.form.name,
							bank_phone: uni.getStorageSync("user_phone"),
							type: 25,
						}
						uni.navigateTo({
							url: "/operate/paymentSign/paymentSign?data=" + JSON.stringify(params)
						})
					}
				}
			},
			handleSearchCompany: debounce(function(company) {
				const _this = this
				if (company) {
					uni.showLoading({
						title: '正在搜索中'
					})
					const params = {
						company_name: company[0]
					}
					const _this = this
					uni.request({
						url: `${env.baseUrl}/api/company_query_name`,
						method: "post",
						data: params,
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': '',
						},
						success(res) {
							_this.showChooseCompany = true
							_this.companyList = res.data.data.list;
							uni.hideLoading()
						}
					})
				}
			}, 1000),
			async onBankText(){
				const require = {
					name: this.form.name,
					company: this.form.company,
					position: this.form.position,
					reference_id: this.reference.id,
				}
        let formNew = {...this.form}
        delete formNew.reference_id
        delete formNew.company
        delete formNew.id_card
        delete formNew.position
				if (hasEmptyValue(formNew) && this.isClick) {
					this.isClick = false
					if (this.addressData.id) {
						const _this = this
						const params = {
							...this.form,
							reference_id: this.reference.id,
							user_id: uni.getStorageSync("user_id")
						}
						const priceRes = await getConfigInfo({
							key: this.reference.id ? 'have_recommend' : 'no_recommend'
						})
						const orderRes = await teaOrderSn()
						const orderParams = {
							type: 'president',
							order_sn: orderRes.data.order_sn,
							userid: uni.getStorageSync("user_id"),
							price: priceRes.data.value,
							pay_type: 1,
							params: JSON.stringify(params)
						}
						const res = await teaCreateOrder(orderParams)
						this.isClick = true
						uni.setStorageSync("bank",res.data)
						uni.navigateTo({
							url: "/teaBureau/teaBankOrder/teaBankOrder"
						})
					} else {
						uni.showToast({
							title: "请完善收货信息",
							icon: "none"
						})
						this.isClick = true
					}
				} else {
					uni.showToast({
						title: "必填项不能为空",
						icon: "none"
					})
					this.isClick = true
				}
			},
			async onWechatPay() {
				const require = {
					name: this.form.name,
					company: this.form.company,
					position: this.form.position,
					reference_id: this.reference.id,
				}
        let formNew = {...this.form}
        delete formNew.reference_id
        delete formNew.company
        delete formNew.position
        delete formNew.id_card
        console.log(formNew,'formNew');

				if (hasEmptyValue(formNew) && this.isClick) {
					this.isClick = false
					if (this.addressData.id) {
						const _this = this
						const params = {
							...this.form,
							reference_id: this.reference.id,
							user_id: uni.getStorageSync("user_id")
						}
						const priceRes = await getConfigInfo({
							key: this.reference.id ? 'have_recommend' : 'no_recommend'
						})
						const orderRes = await teaOrderSn()
						const orderParams = {
							type: 'president',
							order_sn: orderRes.data.order_sn,
							userid: uni.getStorageSync("user_id"),
							price: priceRes.data.value,
							pay_type: 2,
							params: JSON.stringify(params)
						}
						const res = await teaCreateOrder(orderParams)
						await uni.requestPayment({
							provider: "wxpay",
							appId: res.data.order_str.appId,
							timeStamp: res.data.order_str.timeStamp,
							nonceStr: res.data.order_str.nonceStr,
							package: res.data.order_str.package,
							signType: res.data.order_str.signType,
							paySign: res.data.order_str.paySign,
							success() {
								_this.joinCode.show = true
							},
							fail(err) {
								_this.isClick = true
								uni.hideLoading()
								uni.showLoading({
									title: err,
								})
							},
							complete() {
								_this.isClick = true
								uni.hideLoading()
							}
						})
					} else {
						uni.showToast({
							title: "请完善收货信息",
							icon: "none"
						})
						this.isClick = true
					}
				} else {
					uni.showToast({
						title: "必填项不能为空",
						icon: "none"
					})
					this.isClick = true
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.search_btn {
		margin-left: 0;
		margin-right: 0rpx;
		height: 70rpx;
		line-height: 70rpx;
		background: #fb6316;
		color: #fff;
		font-size: 26rpx;
	}

	.report_company_content {
		width: 100%;
		position: absolute;
		background-color: #fff;
		z-index: 10;
		padding: 0 10px;
		height: 230px;
		top: 90rpx;
		left: 0;
	}

	.company_list {
		width: 100%;
		position: absolute;
		background-color: #868B9A;
		z-index: 10;
		padding: 0 10px;
		height: 320rpx;
		top: 100rpx;
		left: 0;
		overflow: auto;
		color: #fff;
		border-radius: 10rpx;
	}

	.reference_name {
		height: 70rpx;
		line-height: 70rpx;
	}

	.checkAddressBox {
		height: 1000rpx;
		padding: 30rpx 30rpx 50rpx 30rpx;

		.address_box {
			padding: 20rpx;
			margin-top: 20rpx;
			border-radius: 10rpx;
			background: #FAFAFA;
		}

		.address_check_box {
			padding: 20rpx;
			margin-top: 20rpx;
			border-radius: 20rpx;
			background: #fb6316;
			color: #fff;
		}

		.addBtn {
			flex: 1;
			height: 80rpx;
			background: #fff;
			color: #000;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
			margin-right: 40rpx;
			border: 1rpx solid #ccc;
		}

		.bottomBtn {
			flex: 1;
			height: 80rpx;
			background: #fb6316;
			color: #fff;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
		}
	}

	.sign_box {
		display: flex;
		justify-content: space-between;
		padding: 25rpx 10rpx 25rpx 0;
		border-radius: 10rpx;
		font-size: 30rpx;

		.agree_name::before {
			content: "*";
			color: #F8494D;
		}
	}

	.require::before {
		content: "*";
		color: #F8494D;
		top: 30rpx;
		position: absolute;
		left: 10rpx;
	}
	
	.common_css{
		color:#fff;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
	}
	
	.confirm_btn{
		height: 80rpx;
		background: #B3723E;
		border-radius: 50rpx;
	}
</style>